package com.gj.xxl.job.admin.core.route.strategy;

import com.gj.xxl.job.admin.core.route.RouteStrategy;
import com.gj.xxl.job.admin.core.trigger.GjJobTrigger;
import com.gj.xxl.job.core.biz.ExecutorBiz;
import com.gj.xxl.job.core.biz.model.ReturnT;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * 故障转移策略
 * 实现思路：简单来说，就是在路由之前，先发一个心跳包，检测一个执行器端是否在正常工作
 * 如果收到了执行器端的心跳响应，说明这个地址没有问题，直接返回就行了；
 * 如果没有接收到响应，说明执行器端出故障了，这个地址不能使用，就继续循环迭代下一个执行器端了。
 */
public class FailOverRouteStrategy implements RouteStrategy {

    private static Logger logger = LoggerFactory.getLogger(FailOverRouteStrategy.class);

    @Override
    public String route(Integer jobId, List<String> addressList) {
        for (String address : addressList) {
            ReturnT beatResult = null;
            try {
                ExecutorBiz client = GjJobTrigger.getInstance().getClient(address);
                beatResult = client.beat();
            } catch (Exception e) {
                logger.warn(">>>>>>>>>>>>>> 执行器: {} 出现故障了！！！", address);
                return null;
            }
            if (beatResult.getCode() == ReturnT.SUCCESS_CODE) {
                return address;
            }
        }
        return null;
    }
}
